/**
 * Excel通用导入功能页面
 */
(function() {

    var _VALID_PATH = "validateservice"; // location中的校验路径的key
    var _IS_VALID_ENABLE = false;
    var _EXCEPTION_EMPTY_VALID_PATH = "未向本功能提供有效的数据校验地址"; // location中的校验路径的key
    var _isImportAbort = false;
    var _dataTableInstance = null;

    // 获取数据校验地址
    var _validPath = _IS_VALID_ENABLE && extractParam(_VALID_PATH);
    if (_IS_VALID_ENABLE && !_validPath) {
        window.top.window.showModalAlert(_EXCEPTION_EMPTY_VALID_PATH);
        return;
    }

    // ====== 方法区 ======
    var _improtFile = function() {
        $("#dataTableContainer").hide();
        if (!this.files) {
            return;
        }

        var f = this.files[0];
        var reader = new FileReader();

        reader.onload = function(e) {
            var data = e.target.result;
            var wb = getWorkBookFromExcel(data);
            if (!wb) {
                return;
            }

            var dataTableOption = getDataTableOptionFromWB(wb);
            var dataJson = getDataFromWB(wb);

            var dataItem;
            if (!_IS_VALID_ENABLE) {
                // 初始化进度条
                resetProgress(dataJson.length);
                for (var i = 0, l = dataJson.length; i < l; i++) {
                    dataItem = dataJson[i];
                    doValidDataItem(dataItem);
                    if (_isImportAbort == true) {
                        // TODO：执行取消导入操作的工作
                        break;
                    }
                    // TODO:更新进度条
                    updateProgress(i+1, l);
                    if(i+1==l){
                        drawDataTable(dataTableOption, dataJson);
                    }
                }
            }
        };

        reader.readAsBinaryString(f);
    }

    var updateProgress = function(now, total) {
        $("#progressbar").attr("aria-valuenow", now + "");
        $("#progressbar").find("#now").html(now + "")
        $("#progressbar").css("width", numberParser(now / total) * 100 + "%");
    }

    var resetProgress = function(total) {
        $("#progressbar").attr("aria-valuetransitiongoal", total);
        $("#progressbar").find("#total").html(total);

        $("#progressbar").attr("aria-valuenow", "0");
        $("#progressbar").find("#now").html("0")
        $("#progressbar").css("width", "0%");
    }

    var doValidDataItem = function(data) {
        var returnResult = {};
//        $.ajax({
//            type : "PUT",
//            url : _validPath,
//            contentType : "application/json;charset=utf-8",
//            data : data,
//            dataType : "json",
//            async : false,
//            success : function(data) {
//                returnResult = data
//            },
//            error : function(XMLHttpRequest, textStatus) {
//                returnResult.result = failed;
//                returnResult.msg = "网络异常";
//            }
//        });

        return returnResult;
    }

    var drawDataTable = function(tableOptions, dataList) {
        if ($.fn.DataTable.isDataTable('#dataTable') && !!_dataTableInstance) {
            _dataTableInstance.destroy();
        }
        $("#dataTableContainer").show();
        _dataTableInstance = $("#dataTable").DataTable(tableOptions).on('draw.dt', function() {
            $("#dataTable").find("th.sorting_asc").removeClass("sorting_asc");
            $("#dataTable").tooltip({
                selector : ".tooltip-column-detail",
                container : "body",
                title : function() {
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });
        });

        _dataTableInstance.rows.add(dataList).draw();
    }

    var getDataFromWB = function(wb) {
        sheetName = wb.SheetNames[0]; // 初始化表格名称
        sheetData = wb.Sheets[sheetName]; // 初始化表格数据

        // 生成我们需要的JSON
        var jsonData = XLSX.utils.sheet_to_json(sheetData, {
            defval : ""
        });

        for (var i = 0, l = jsonData.length; i < l; i++) {
            for ( var key in jsonData[i]) {
                var newKey = /\((\D+)\)/.exec(key)[1];
                jsonData[i][newKey] = jsonData[i][key];
                delete (jsonData[i][key]);
            }
        }
        return jsonData;
    }

    var getDataTableOptionFromWB = function(wb) {
        sheetName = wb.SheetNames[0]; // 初始化表格名称
        sheetData = wb.Sheets[sheetName]; // 初始化表格数据

        // 生成我们需要的JSON
        var jsonData = XLSX.utils.sheet_to_json(sheetData, {
            defval : ""
        });

        var keyNameMap = {};

        for ( var key in jsonData[0]) {
            var splitIndex = key.indexOf("(");
            var title = key.substring(0, splitIndex);
            var newKey = /\((\D+)\)/.exec(key)[1];

            keyNameMap[newKey] = title;
        }

        for (var i = 0, l = jsonData.length; i < l; i++) {
            for ( var key in jsonData[i]) {
                var newKey = /\((\D+)\)/.exec(key)[1];
                jsonData[i][newKey] = jsonData[i][key];
                delete (jsonData[i][key]);
            }
        }

        var columns = [];
        var orderColumn = {
            "className" : "truncate-text tooltip-column-detail",
            "data" : "__rowNum__",
            "orderable" : false,
            "title" : "序号"
        }
        columns.push(orderColumn);
        for ( var key in jsonData[0]) {
            var optionValue = {
                className : "truncate-text tooltip-column-detail",
                orderable : false,
            }
            optionValue.title = keyNameMap[key];
            optionValue.data = key;
            columns.push(optionValue);
        }
        return {
            "processing" : true,
            "serverSide" : false,
            "dom" : '<"bottom"rtflp>',
            "searching" : false,
            "destroy" : true,
            "scrollY" : "500px",
            "scrollCollapse" : false,
            "paging" : false,
            "select" : {
                items : 'row'
            },
            "columns" : columns
        };
    }

    // 从excel获取wb数据
    var getWorkBookFromExcel = function(excelObj) {
        var wb = XLSX.read(excelObj, {
            type : 'binary'
        });

        if (!isExcelDataValid(wb)) {
            return null;
        } else {
            return wb;
        }
    }

    var isExcelDataValid = function(workbook) {
        // TODO: 校验Excel对应的workbook信息是否正确
        return true;
    }

    $("#upload-file").unbind("change").bind("change", _improtFile);
})();

// ===========公共方法==========

//获取页面location中的URL参数值
function extractParam(paramName) {
    var returnString = "";
    var str = window.location.search;
    if (!!str) {
        returnString = GetArgsFromHref(str, paramName);
    }
    return returnString;
}

// 从URL字符串中获取参数值
function GetArgsFromHref(sHref, sArgName) {
    var args = sHref.split("?");
    var retval = "";

    if (args[0] == sHref) /*参数为空*/
    {
        return retval;
        /*无需做任何处理*/
    }
    var str = args[1];
    args = str.split("&");
    for (var i = 0; i < args.length; i++) {
        str = args[i];
        var arg = str.split("=");
        if (arg.length <= 1)
            continue;
        if (arg[0] == sArgName)
            retval = arg[1];
    }
    return retval;
}

// 小数点保留两位
var numberParser = function(data) {
    var returnValue = "-";
    var numberData = parseFloat(data);
    if (numberData === +numberData) {
        returnValue = numberData.toFixed(2);
    }
    return returnValue;
}

//根据列索引获取所在列的列字母
var getCharCol = function(n) {
    var temCol = '';
    var s = '';
    var m = 0;
    while (n > 0) {
        m = n % 26 + 1;
        s = String.fromCharCode(m + 64) + s;
        n = (n - m) / 26;
    }
    return s;
};

// 根据字母获取所在列的列索引
var getNumCol = function(c) {
    var num = 0;
    var result = 0;
    for (var i = 0; i < c.length; i++) {
        var ch = c[i];
        num = parseInt(ch.charCodeAt() - 'A'.charCodeAt() + 1);
        num *= Math.pow(26, i);
        result += num;
    }
    return result;
};